﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace Sockets2
{
    public partial class ServidorUI : Form
    {
        public ServidorUI()
        {
            InitializeComponent();
        }

        Servidor s = new Servidor();
        int cantCon = 0;
        string Log { get { return txtLog.Text; } set { txtLog.Text += value + "\r\n"; } }
        string Recibido { set { txtRecibir.Text += value + "\r\n"; } }

        private void Form1_Load(object sender, EventArgs e)
        {
          //  this.Text = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First().ToString();
            new Thread(new ThreadStart(
                delegate
                {
                    s.Start();
                }
                        )).Start();  
         
        }

        private void button1_Click_3(object sender, EventArgs e)
        {

        }

        private void Cerrar(object sender, EventArgs e)
        {
            s.cerrar();
            Application.Exit();
        }

        void chequearSolicitudes()
        {
            if (s.solicitudEntrante() == true)
            {
                txtLog.Text += "Hay una solicitud entrante \r\n";
                s.AceptaConexion();
                txtLog.Text += "Conexion aceptada: id=" + (cantCon+1).ToString() + "\r\n";
                cantCon += 1;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            chequearSolicitudes();


            for (int i = 0; i < cantCon; i++)
            {
                if (s.nuevoMsj(i))
                {
                    Recibido = s.recibir(i);
                }
                
            }
        }
        private void txtEnviar_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                for (int i = 0; i < cantCon; i++)
                {
                    s.enviar(txtEnviar.Text, i);
                }
                txtEnviar.Text = "";
            }
        }

        private void txtEnviar_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtRecibir_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < cantCon; i++)
            {
                s.enviarArchivo(i);
            }
           
            
        }

    }





  
}
